﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;

public class Booter : MonoBehaviour {
    public bool Reset = false;
    //    [HideInInspector]
    public bool inited = false;
    private static Booter _instance;

    public static Booter Instance {
        get {
            if (_instance == null) {

                GameObject o = new GameObject ("Booter");

                _instance = o.AddComponent<Booter> ();
            }
            return _instance;
        }
    }

    private void Awake () {
        Booter[] booter = FindObjectsOfType<Booter> ();
        if (booter.Length > 1) {
            Destroy (this.gameObject);
            return;
        }
        _instance = this;
        DontDestroyOnLoad (this.gameObject);
        #region 不需要等待同步数据时
        InitAllManager ();
        inited = true;
//        DG.Tweening.DOTween.SetTweensCapacity (500, 150);
        #endregion 
    }

    //使用反射初始化所有manager
    private void InitAllManager () {

        print ("开始初始化所有Manager------------------------------------------>");
        var managerType = typeof (Imanager);
        List<Imanager> controllerList = new List<Imanager> ();
        var types = Assembly.GetCallingAssembly ().GetTypes ();
        foreach (var i in types) {
            Type[] tps = i.GetInterfaces ();
            foreach (var tf in tps) {
                if (tf.FullName == managerType.FullName) {
                    if (i.ContainsGenericParameters) continue;
                    Imanager con = Activator.CreateInstance (i) as Imanager;
                    controllerList.Add (con);
                }
            }
        }
        foreach (var item in controllerList) {

            item.InitManager ();
        }
        foreach (var item in controllerList) {
            item.StartManager ();
        }
        print ("Manager初始化结束----------------------------------------------->");

    }

    IEnumerator Init () {
        if (inited) yield break;
#if UNITY_EDITOR
        if (Reset)
            PlayerPrefs.DeleteAll ();
#endif
        //AB包加载
        //ABLOADER ------------>

        //加载依赖模块        
        yield return LoadDependent ();

        //初始化所有manager
        InitAllManager ();

        yield return 1;

        inited = true;
    }

    IEnumerator LoadDependent () {
        yield return null;
    }

}